package com.example;

/**
 * @ClassName FalseSharingTest
 * @Description 伪共享    -XX:-RestrictContended
 * @Author: XMK
 * @Date: 2021/4/12 11:42
 * @Version: 1.0
 */

public class FalseSharingTest {

    public static void main(String[] args) throws InterruptedException {
        testPointer(new Pointer2());
    }

    private static void testPointer(Pointer2 pointer) throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100000000; i++) {
                pointer.x.value++;
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100000000; i++) {
                pointer.y.value++;
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println(System.currentTimeMillis() - start);
        System.out.println(pointer.x.value);
        System.out.println(pointer.y.value);
    }
}

class Pointer2 {
    MyLong2 x = new MyLong2();
    MyLong2 y = new MyLong2();
}

@sun.misc.Contended
class MyLong2 {
    volatile long value;
}